package cn.jieruoda.eb.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;

/**
 * 跨域配置
 */
@Configuration
public class CorsConfig implements WebMvcConfigurer {

    // 允许的请求方法
    private static final String[] ALLOWED_METHODS = {
        "GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"
    };
    
    // 允许的请求头
    private static final String[] ALLOWED_HEADERS = {
        "Origin", "X-Requested-With", "Content-Type", "Accept", 
        "Authorization", "Cache-Control", "Pragma", "Expires"
    };

    /**
     * 全局跨域配置
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 允许跨域的路径
                .allowedOriginPatterns("*") // 允许所有域名
                .allowedMethods(ALLOWED_METHODS) // 允许的请求方法
                .allowedHeaders("*") // 允许所有请求头
                .exposedHeaders("Authorization") // 允许前端访问的响应头
                .allowCredentials(true) // 是否允许证书
                .maxAge(3600); // 跨域允许时间
    }

    /**
     * 跨域过滤器
     */
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        
        // 设置允许的前端域名
        config.setAllowedOriginPatterns(Arrays.asList("*")); // 开发环境允许所有域名
        
        // 允许的请求头和方法
        config.addAllowedHeader("*");
        config.setAllowedMethods(Arrays.asList(ALLOWED_METHODS));
        
        // 允许携带认证信息
        config.setAllowCredentials(true);
        
        // 允许前端访问的响应头
        config.setExposedHeaders(Arrays.asList("Authorization"));
        
        // 预检请求的有效期
        config.setMaxAge(3600L);
        
        // 对所有接口都有效
        source.registerCorsConfiguration("/**", config);
        
        return new CorsFilter(source);
    }
}
